﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace dataSendModel.Util
{
    public class TcpClientHelper
    {

        private TcpClient tcp = null;
        private NetworkStream workStream = null;
        private string ip = "";
        private string port = "";
        private byte[] data = null;
        public ManualResetEvent connectDone = new ManualResetEvent(false);

        public TcpClientHelper(string ip, string port)
        {
            this.ip = ip;
            this.port = port;
        }

        public TcpClient Tcp
        {
            get { return tcp; }
        }

        public NetworkStream WorkStream
        {
            get { return workStream; }
        }

        public byte[] Data
        {
            get { return data; }
        }


        // 异步连接
        public void Connect()
        {
            if ((tcp == null) || (!tcp.Connected))
            {

                tcp = new TcpClient();
                tcp.ReceiveTimeout = 10;

                connectDone.Reset();

                tcp.BeginConnect(ip, int.Parse(port),
                    new AsyncCallback(ConnectCallback), tcp);

                connectDone.WaitOne();

                //if ((tcp != null) && (tcp.Connected))
                //{
                //    workStream = tcp.GetStream();

                //    asyncread(tcp);
                //}

            }
        }



        // 异步连接的回调函数
        private void ConnectCallback(IAsyncResult ar)
        {
            connectDone.Set();
            TcpClient t = (TcpClient)ar.AsyncState;

            if (t.Connected)
            {
                t.EndConnect(ar);
            }

        }


        // 异步读取采集服务器数据
        public void asyncread()
        {
            if ((tcp != null) && (tcp.Connected))
            {
                StateObject state = new StateObject();
                state.client = tcp;
                NetworkStream stream = tcp.GetStream();

                if (stream.CanRead)
                {

                    IAsyncResult ar = stream.BeginRead(state.buffer, 0, StateObject.BufferSize,
                            new AsyncCallback(TCPReadCallBack), state);

                }
            }
        }


        // TCP读数据的回调函数
        private void TCPReadCallBack(IAsyncResult ar)
        {

            StateObject state = (StateObject)ar.AsyncState;
            //主动断开时
            if ((state.client == null) || (!state.client.Connected))
            {
                return;
            }
            int numberOfBytesRead;
            NetworkStream mas = state.client.GetStream();

            numberOfBytesRead = mas.EndRead(ar);
            state.totalBytesRead += numberOfBytesRead;

            if (numberOfBytesRead > 0)
            {
                byte[] dd = new byte[numberOfBytesRead];
                Array.Copy(state.buffer, 0, dd, 0, numberOfBytesRead);
                data = dd;
                mas.BeginRead(state.buffer, 0, StateObject.BufferSize,
                        new AsyncCallback(TCPReadCallBack), state);
            }
            else
            {
                //被动断开时                
                mas.Close();
                state.client.Close();
                mas = null;
                state = null;
            }
        }


        // 断开连接
        public void DisConnect()
        {
            if ((tcp != null) && (tcp.Connected))
            {
                workStream.Close();
                tcp.Close();
            }
        }

    }
    public class StateObject
    {
        public TcpClient client = null;
        public int totalBytesRead = 0;
        public const int BufferSize = 1024;
        public string readType = null;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder messageBuffer = new StringBuilder();
    }
}
